# -*- coding: utf-8 -*-
from odoo import models, fields, api, tools, _
from odoo.exceptions import ValidationError, Warning
from lxml import etree

from datetime import datetime
import random
import time
import datetime
from dateutil import tz
from dateutil.tz import tzlocal
# import urlparse
import logging
_logger = logging.getLogger(__name__)
# 标识牌功能模块相关

class IdentificationCard(models.Model):
    """
    标识牌
    """
    _name = "tyibs.main.identification.card"
    _rec_name = "qrcode"
    _order = 'id desc'

    qrcode = fields.Char(string=u"标识编号",required=True) # 二维码编号
    code = fields.Char(string=u"编号",compute="_computed_code",store=True) # 纯粹为了展示用，不让标识牌展现出URL地址
    rfid_code = fields.Char(string=u"RFID号",required=True) # NFC芯片卡号
    card_type = fields.Selection([('identification',u'标识牌'),('position',u'部位牌'),('property',u'物业卡')],string=u"标牌类型",default='position')
    get_time = fields.Datetime(string=u'入库时间',default= lambda self:fields.Datetime.now())
    install_state = fields.Selection([('install',u'已安装'),('uninstall',u'未安装')],default='uninstall',string=u"安装状态")
    bind_time = fields.Datetime(string=u'绑定时间')
    maintenance_company_id = fields.Many2one("tyibs.base.maintenance.company", string=u"维保公司") # 电梯今后更换维保公司也不需要更改此字段
    use_company_id = fields.Many2one("tyibs.base.lift.use.company", string=u"使用单位")
    lift_id = fields.Many2one("tyibs.base.lift", string=u"所属电梯",ondelete="cascade")
    lift_part_id = fields.Many2one("tyibs.main.lift.part",string=u"所属电梯部位",domain="[('lift_id', '=', lift_id)]")
    # photo = fields.Binary(string=u"绑定照片", attachment=True, public=True)

    _sql_constraints = [
        ("unique_qrcode", "unique(qrcode)", u"二维码有重复！"),
        ("unique_rfid_code", "unique(rfid_code)", u"RFID码有重复！")
    ]

    def url2dist(self,url):
        # query = urlparse.urlparse(url).query
        # return dict([(k, v[0]) for k, v in urlparse.parse_qs(query).items()])
        code_all = url.split('/lift/detail/', 1 )
        # 这个防止万一它带了参数
        code = code_all[1].split('?',1)[0]
        return {'code':code}

    # 获取展示用code
    @api.depends('qrcode')
    def _computed_code(self):
        for card in self:
            if card.qrcode:
                if '/lift/detail/' in card.qrcode:
                    card.code = card.url2dist(card.qrcode)['code']
                else:
                    card.code = card.qrcode

    # 逻辑上只有大卡在创建或者修改的时候需要去同步电梯的二维码号和射频卡号
    @api.model
    def create(self, vals):
        new_self = super(IdentificationCard, self).create(vals)
        card_type = new_self.card_type
        lift_id = new_self.lift_id
        if card_type=='identification' and lift_id:
            # 去同步电梯的资料
            lift_id.sudo().write({
                'rfid_code':new_self.rfid_code,
                'code':new_self.url2dist(new_self.qrcode)['code'],
                'card_install_state':'installed'
            })
            # 否则同步电梯部位的资料
        elif card_type=='position' and new_self.lift_part_id:
            new_self.lift_part_id.sudo().write({
                'rfid_code':new_self.rfid_code,
                'qrcode':new_self.qrcode
            })
        elif card_type=='property':
            if new_self.use_company_id:
                new_self.use_company_id.sudo().write({
                    'rfid_code':new_self.rfid_code,
                    'qr_code':new_self.qrcode
                })
        return new_self

    @api.multi
    def write(self, vals):
        # 区县局修改物业卡使用单位
        old_use_company_id = self.use_company_id
        new_self = super(IdentificationCard, self).write(vals)
        if self.card_type=='identification' and self.lift_id:
            self.lift_id.sudo().write({
                'rfid_code':self.rfid_code,
                'code':self.url2dist(self.qrcode)['code'],
                'card_install_state':'installed'
            })
        elif self.card_type=='position' and self.lift_part_id:
            self.lift_part_id.sudo().write({
                'rfid_code':self.rfid_code,
                'qrcode':self.qrcode
            })
        elif self.card_type=='property':
            if vals.get("use_company_id", False):
                # 如果变更了使用单位，旧的单位上的二维码个rfid码清除，新的加上
                if old_use_company_id:
                    old_use_company_id.write({
                        'rfid_code': False,
                        'qr_code': False
                    })

                if self.use_company_id:
                    self.use_company_id.sudo().write({
                        'rfid_code':self.rfid_code,
                        'qr_code':self.qrcode
                    })
                    new_self = super(IdentificationCard, self).write({'install_state':'install','bind_time':datetime.datetime.utcnow()})
        return new_self

    @api.model
    def fields_view_get(self, view_id=None, view_type='form', toolbar=False, submenu=False):
        context = self._context or {}
        res = super(IdentificationCard, self).fields_view_get(view_id=view_id, view_type=view_type,
                                                toolbar=toolbar, submenu=False)
        if (res['type'] == "form" or res['type'] == 'tree'):
            doc = etree.XML(res['arch'])
            form_xpath = doc.xpath("//{}".format(res['type']))[0]
            if context.get("readonly", False):
                # asset_id = self.env.context.get('active_id')
                # active_model = self.env.context.get('active_model')
                # if context.get("form_no_edit", False) == 'no':
                form_xpath.set("create", "false")
                form_xpath.set("edit", "false")
                form_xpath.set("delete", "false")
                res['arch'] = etree.tostring(doc)
            elif context.get("write_only", False):
                form_xpath.set("create", "false")
                form_xpath.set("delete", "false")
                res['arch'] = etree.tostring(doc)
        return res


class DistributionCard(models.Model):
    """
    签收单
    """
    _name = "tyibs.main.distribution.card"
    _rec_name = "distribution_code"
    _order = 'id desc'

    distribution_code = fields.Char(string=u"签收单号",required=True) # 唯一标识
    maintenance_company_id = fields.Many2one("tyibs.base.maintenance.company", string=u"维保公司",required=True)
    distribution_time = fields.Datetime(string=u'分配时间',default= lambda self:fields.Datetime.now())

    # 此处视情况后面再看要不要绑定其他角色
    distribution_user_id = fields.Many2one('res.users',string=u"分配人",default=lambda self:self.env.uid)
    contact = fields.Char(string=u"签收人")
    phone = fields.Char(string=u"联系电话")
    distribution_num = fields.Integer(string=u"卡牌总数")
    identification_card_num = fields.Integer(string=u"标识牌数量")
    position_card_num = fields.Integer(string=u"部位卡数量")

    _sql_constraints = [
        ("unique_distribution_code", "unique(distribution_code)", u"分配单号有重复！")
        ]
    
    # 自动生成默认分配单号
    @api.onchange('distribution_time')
    def _onchange_distribution_time(self):
        if not self.distribution_code:
            self.distribution_code = self.env['ir.sequence'].next_by_code('tyibs.main.distribution.card.discode')